package com.sj.utils;

import cn.hutool.core.util.StrUtil;
import com.sj.common.exception.CustomException;
import com.sj.common.lang.Const;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2021/5/11
 * Time: 下午 17:59
 * Description: Jwt工具类
 *
 * @author xiaoqi
 */
@Data
@Component
public class JwtUtils {
    /**
     * 秘钥
     */
    @Value("${know.jwt.secret}")
    private String secret;
    /**
     * 过期时间
     */
    @Value("${know.jwt.expire}")
    private Long expire;
    /**
     * 头名字
     */
    @Value("${know.jwt.header}")
    private String header;

    /**
     * 生成token
     *
     * @param sub 接收用户
     * @return token值
     */
    public String generateToken(String sub) {
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(sub)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expire * 1000))
                .signWith(SignatureAlgorithm.HS256, secret).compact();
    }

    /**
     * 解析token
     *
     * @param token 需要解析的token字符串
     * @return
     */
    public Claims resolverToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 判断token是否失效
     *
     * @param claims
     * @return
     */
    public boolean tokenIsExpired(Claims claims) {
        // 失效时间是否在当前时间之前
        return claims.getExpiration().before(new Date());
    }

    public Claims checkToken() {
        return this.checkToken(RequestUtils.getRequest());
    }

    public Claims checkToken(HttpServletRequest request) {
        // 如果有 AuthCheck修饰 则需要判断是否登陆
        String bearerToken = request.getHeader(header);

        if (StrUtil.isEmpty(bearerToken)) {
            throw new CustomException("认证错误，请先登录");
        }

        if (!bearerToken.startsWith(Const.TOKEN_PREFIX)) {
            throw new CustomException("认证错误，错误的令牌");
        }

        String[] tokens = bearerToken.split(" ");
        if (tokens.length != 2) {
            throw new CustomException("认证错误，错误的令牌");
        }

        String token = tokens[1];
        Claims claims = this.resolverToken(token);
        if (claims == null) {
            throw new CustomException("认证错误，错误的令牌");
        }

        if (this.tokenIsExpired(claims)) {
            throw new CustomException("认账错误，令牌已过期");
        }
        return claims;
    }


}